package view;

import java.awt.event.MouseListener;
import java.util.Observable;
import java.util.Set;

import javax.swing.JFrame;
import javax.swing.JList;

import entity.Book;
import java.util.Observer;
import javax.swing.DefaultListModel;
import javax.swing.ListSelectionModel;

/**
 * @author s759487
 * @version 1.0
 * @created 11-Apr-2011 16:31:14
 */
public class ListView extends JFrame implements Observer {

    //private java.util.Set<Book> books = new java.util.HashSet<Book>();
    private DefaultListModel listModel = new DefaultListModel();

    public ListView(java.util.List<Book> books, MouseListener ml) {
        setSize(800, 200);
        String[] rows = new String[books.size()];
        int i = 0;
        for (Book b : books) {
            listModel.addElement("[" + b.getId() + "] " + b.getAuthor() + " - " + b.getTitle());
            b.addObserver(this);
        }
        JList jlist = new JList();
        jlist.setModel(listModel);
        jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jlist.addMouseListener(ml);
        add(jlist);
        setVisible(true);
    }

    public void update(Observable o, Object arg) {
        Book b = (Book) o;
        listModel.setElementAt(
                "[" + b.getId() + "] " +
                b.getAuthor() + " - " +
                b.getTitle() + 
                " (state: " + b.getState() +
                (!b.getLentTo().equals("")? " ,borrowed by: " + b.getLentTo() : "") +
                (!b.getReservedBy().equals("")? " ,reserved by: " + b.getReservedBy() : "") +
                ")"
                , b.getId()
        );
    }
}
